#include<iostream>
#include<vector>

using namespace std;
vector<int> tmp;
static int ret = 0;
void  reversePairssum(vector<int>& nums, int left, int right, int ret)
{
    if (left >= right) return;

    int mid = (left + right) >> 1;
    reversePairssum(nums, left, mid - 1, ret);
    reversePairssum(nums, mid + 1, right, ret);

    int cur1 = left, cur2 = mid + 1, i = 0;
    while (cur1 <= mid && cur2 <= right)
    {
        if (nums[cur1] <= nums[cur2])
        {
            tmp[i++] = nums[cur1++];
        }
        else
        {
            tmp[i++] = nums[cur2++];
            ret += mid - left + 1;
        }
    }
    while (cur1 <= mid) tmp[i++] = nums[cur1++];
    while (cur2 <= right) tmp[i++] = nums[cur2++];

    for (int i = left; i <= right; i++)
    {
        nums[i] = tmp[i - left];
    }
}
int reversePairs(vector<int>& nums) {
    tmp.resize(nums.size());
    
    reversePairssum(nums, 0, nums.size() - 1, ret);
    return ret;
}



int main()
{
    vector<int> nums = { 9, 7, 5, 4, 6 };
    cout<<reversePairs(nums);
    
    cout << endl;
    return 0;
}
